package com.sx.utils;

import com.sx.config.EmailProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.SimpleEmail;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Arrays;

/**
 * QQ邮箱提醒雨课堂情况
 */
@Slf4j
@Component
public class EmailUtils {
    @Resource
    private  EmailProperties emailProperties;

    /**
     * 发送邮件
     */
    public void GetEmailCode(String message) {
        try {
            // 创建邮箱对象
            SimpleEmail mail = new SimpleEmail();
            // 设置发送邮件的服务器
            mail.setHostName("smtp.qq.com");
            // "你的邮箱号"+ "上文开启SMTP获得的授权码"
            mail.setAuthentication(emailProperties.getFromAddress(), emailProperties.getPassword());
            // 发送邮件 "你的邮箱号"+"发送时用的昵称"
            mail.setFrom(emailProperties.getFromAddress(), "您的雨课堂小助手");
            // 发送服务端口
            mail.setSslSmtpPort(String.valueOf(465));
            // 使用安全链接
            mail.setSSLOnConnect(true);
            System.setProperty("mail.smtp.ssl.enable", "true");
            System.setProperty("mail.smtp.ssl.protocols", "TLSv1.2");
            // 接收用户的邮箱
            mail.addTo(emailProperties.getToAddress());
            // 邮件的主题(标题)
            mail.setSubject("今日课堂情况提醒");
            // 邮件的内容
            mail.setMsg(message);
            // 发送
            mail.send();
            log.info("邮件发送成功:{}", Arrays.toString(emailProperties.getToAddress()));
        } catch (EmailException e) {
            log.error("邮件发送失败", e);
        }
    }

}
